iT邦幫忙

2023 iThome 鐵人賽

DAY 22
0
Vue.js

.NET Core與Vue3組合開發技系列 第 22

[Day 22] 父子組件常見操作_part2.($emit事件監聽)

  • 分享至 

  • xImage
  •  

對於 Vue 中的Component,不僅能透過 props 從外部向組件傳入資料,還可以
在組件內部與外部父組件進行互動,一般可以透過事件來解決。

在父組件透過 v-on(可縮簡只寫@ 即可)監聽子組件上拋出來的事件。
一般而言會有以下幾步
Step1.在父組件和子組件透過 v-on 指令建立事件的勾稽。
Step2.在子組件指定觸發什麼類型的事件,比方:單擊、雙擊等。
Step3.在父組件中指定事件觸發的行為,如改變文字樣式、執行一段JS code等。

在子組件ChildComponent.vue 中,寫以下code:

<template>
    <button @click="$emit('chTextSize')">改變大小</button>
    <div>
        <span>Sub Component</span>
    </div>
</template>

在此程式碼中,只有< template >模板程式碼,核心程式碼是< button >按鈕上的事件。
子組件去呼叫 Vue 內建的$emit()方法,藉由傳入父組件指定的事件名稱"chTextSize"來拋出一個Event。

在 < button >上指定的事件類型是@click,也就是點選事件,當User點擊了此按鈕,會傳遞給父組件的'chTextSize'事件。父組件中的'chTextSize'事件監聽到之後,會接收這事件。

於 App.vue 根組件中匯入 ChildComponent.vue 子組件,App.vue 此時相對屬於是父組件。

<template>
  <main>
    <div :style="{ fontSize: FontSize + 'em' }">
      <ChildComponent msg="訊息" @chTextSize="FontSize+=0.1" />
    </div>
  </main>
</template>

<script setup>
  import ChildComponent from './components/ChildComponent.vue';
  import { ref } from 'vue';
  const FontSize = ref(1);
</script>

@chTextSize="FontSize+=0.1"事件的功能是在子組件中每單擊一次,則執行 FontSize 變數大小值+0.1。
此時我們定義的 FontSize 是一個響應式的變樹,可以即時更新到 DOM 上套用樣式效果。
在子組件< ChildComponent/ >標記外部,使用< div >包裹起來,
並透過:style 指定樣式:"{ fontSize: FontSize + 'em' },
只要改變了 FontSize 變數的值,就會讓< ChildComponent/ >子組件中的文字字體大小持續變大。

效果

https://ithelp.ithome.com.tw/upload/images/20231001/20107452yq6dqubOiR.png

https://ithelp.ithome.com.tw/upload/images/20231001/2010745206A0y7000Y.png

本篇已同步發表至個人部落格
https://coolmandiary.blogspot.com/2023/10/2023day-22-part2emit.html


上一篇
[Day 21] 父子組件常見操作_part1.(props,defineProps)
下一篇
[Day 23] 父子組件常見操作_part3.(slots插槽)
系列文
.NET Core與Vue3組合開發技30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言